/* Parsing of declarations. */

#include "defs.h"
#include "data.h"
#include "decl.h"

/*
 * Parse the current token and return
 * a primitive type enum value.
 */
int parse_type(int tk)
{
    switch (tk) {
    case T_CHAR:    return P_CHAR;
    case T_INT:     return P_INT;
    case T_VOID:    return P_VOID;
    default:        fatald("Illegal type, token", tk);
    }
}

/*
 * Parse the declaration of a variable.
 */
void var_declaration(void)
{
    int id, type;

    /* Ensure we have an 'int' token followed by an identifier 
       and a semicon. Text now has the identifier's name. Add it
       as a known identifier. */
    type = parse_type(Token.token);
    scan(&Token);
    ident();
    id = addglob(Text, type, S_VARIABLE);
    genglobsym(id);
    semi();
}

/*
 * Parse the declaration of a function.
 */
struct ASTnode *function_declaration(void)
{
    int id, type;
    struct ASTnode *tree;

    type = parse_type(Token.token);
    scan(&Token);
    ident();
    id = addglob(Text, type, S_FUNCTION);
    lparen();
    rparen();
    tree = compound_statement();

    return mkastunary(A_FUNCTION, type, tree, id);
}
